package org.zoomdev.zoom.dao.configs;

import org.zoomdev.zoom.dao.DaoException;
import org.zoomdev.zoom.dao.SqlConfig;
import org.zoomdev.zoom.dao.driver.SqlDriver;
import org.zoomdev.zoom.dao.entity.Entity;
import org.zoomdev.zoom.dao.entity.Field2ColumnMappingConfig;


public class Delete {


    private final SqlDriver driver;

    public Delete(SqlDriver driver) {
        this.driver = driver;
    }

    public void clear() {

    }


    public String buildSql(SqlConfig cfg, Where where) {
        StringBuilder sql = cfg.getSqlBuilder();
        sql.append("DELETE FROM ");
        driver.protectTable(sql, cfg.getTable());
        where.append(sql);
        return sql.toString();
    }

    public void prepare(SqlConfig cfg, Entity entity, Object data) {
        Where where = cfg.getWhere();
        cfg.setTable(entity.getTableName());
        if (!where.hasCondition()) {
            if (entity.getPrimaryKeys() != null) {
                for (Field2ColumnMappingConfig pk : entity.getPrimaryKeys()) {
                    Object value = pk.get(data);
                    if (value == null) {
                        throw new DaoException("主键值为null:" + pk.getColumnName());
                    }
                    where.where(pk, value);
                }
            }
            if (!where.hasCondition()) {
                throw new DaoException("至少需要一个where条件");
            }
        }

        if (cfg.getTable() == null) {
            cfg.setTable(entity.getTableName());
        }

    }


}
